package com.auto.learning.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.auto.learning.R;
import com.auto.learning.adapter.HomePageListViewAdapter;
import com.auto.learning.adapter.TabViewPagerAdapter;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.SearchBean;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.fragment.SearchAnchorFragment;
import com.auto.learning.fragment.SearchBookFragment;
import com.auto.learning.fragment.SearchComprehensiveFragment;
import com.auto.learning.fragment.SearchMrtFragment;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.SharedPreferencesUtils;
import com.auto.learning.view.SlidingTabLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

public class SearchActivity extends FragmentActivity {

	private SlidingTabLayout search_sliding_tabs;
	private TextView tv_search;
	private EditText et_key;
	private String mTabTitle[] = new String[] { "综合", "书籍", "主播", "大咖秀" };
	private ViewPager viewPager;
	private ArrayList<Fragment> fragmentArrayList = new ArrayList<Fragment>();
	private static final int TOP_GETDATA_SUCCESS = 1001;
	private static final int GETDATA_FAIL = 1002;
	private SearchComprehensiveFragment comprehensiveFragment;
	private SearchMrtFragment mrtFragment;
	private SearchBookFragment bookFragment;
	private SearchAnchorFragment anchorFragment;
	SearchBean searchBean;
	private ImageView image_close;
	// 用来展示热门推荐
	private ListView lv_top;
	private String key;
	// 热门推荐
	private HomePageListViewAdapter topadapter;
	LinearLayout lin_layout;
	private ArrayList<BookBean> bookList;
	private Handle handle = new Handle(this) {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				ResponeResult responeResult = (ResponeResult) msg.obj;
				if (responeResult != null) {
					SearchBean m_searchBean = new Gson().fromJson(
							responeResult.getData(),
							new TypeToken<SearchBean>() {
							}.getType());
					comprehensiveFragment.setSearchBean(m_searchBean);
					mrtFragment.setList(m_searchBean.getHofModel());
					bookFragment.setList(m_searchBean.getBookModel());
					anchorFragment.setList(m_searchBean.getAnchorModel());
					boolean isshow=false;
					if(m_searchBean.getHofModel()!=null&&m_searchBean.getHofModel().size()>0){
						isshow=true;
					}
					if(m_searchBean.getBookModel()!=null&&m_searchBean.getBookModel().size()>0){
						isshow=true;
					}
					isshow(isshow);
					setKey(et_key.getText().toString());
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(et_key.getWindowToken(), 0);
					
				}else{
					isshow(false);
				}
				break;
			case HttpRequestHelper.GETDATA_FAIL:
				CommonMethod.makeNotice(SearchActivity.this, msg.obj.toString()
						+ "");
				isshow(true);
				break;
			case TOP_GETDATA_SUCCESS:
				break;
			case GETDATA_FAIL:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		initFragment();
		initView();
		registerEvent();
		TemporaryVariable.activities.push(this);
		et_key.requestFocus();
//		handle.postDelayed(new Runnable() {
//
//			@Override
//			public void run() {
//				
//				InputMethodManager imm = (InputMethodManager) et_key
//						.getContext().getSystemService(
//								Context.INPUT_METHOD_SERVICE);
//				imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
//			}
//		}, 500);
	}

	private void isshow(boolean isshow) {
		if (!isshow) {
			search_sliding_tabs.setVisibility(View.GONE);
			viewPager.setVisibility(View.GONE);
			lin_layout.setVisibility(View.VISIBLE);
		} else {
			search_sliding_tabs.setVisibility(View.VISIBLE);
			viewPager.setVisibility(View.VISIBLE);
			lin_layout.setVisibility(View.GONE);
		}
	}

	public void getTopWeekBookList() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String
				.valueOf(SharedPreferencesUtils.getParam(this,
						HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair(HttpRequestHelper.PAGE_INDEX, String
				.valueOf(0)));
		params.add(new BasicNameValuePair(HttpRequestHelper.PAGE_SIZE, String
				.valueOf(10)));
		HttpRequestHelper.getGuessYouLike(this, HttpRequestHelper.WEEK_RANK,
				params, handle, TOP_GETDATA_SUCCESS, GETDATA_FAIL);
	}

	private void initView() {
		searchBean = new SearchBean();
		image_close = (ImageView) findViewById(R.id.image_close);
		search_sliding_tabs = (SlidingTabLayout) findViewById(R.id.search_sliding_tabs);
		TabViewPagerAdapter adapter = new TabViewPagerAdapter(
				getSupportFragmentManager(), this, fragmentArrayList, mTabTitle);
		viewPager = (ViewPager) findViewById(R.id.viewpager);
		viewPager.setOffscreenPageLimit(mTabTitle.length);
		viewPager.setAdapter(adapter);
		search_sliding_tabs.setBackgroundColor(getResources().getColor(
				R.color.black));
		search_sliding_tabs.setCustomTabView(R.layout.tab_text,
				R.id.tv_tab_content, R.color.main_green_color,
				R.color.main_grake_color);
		search_sliding_tabs.setDistributeEvenly(true);
		search_sliding_tabs.setViewPager(viewPager);
		search_sliding_tabs.setSelectedIndicatorColors(getResources().getColor(
				R.color.black));
		et_key = (EditText) findViewById(R.id.et_key);
		tv_search = (TextView) findViewById(R.id.tv_search);
		lv_top = (ListView) findViewById(R.id.lv_top);
		lin_layout = (LinearLayout) findViewById(R.id.lin_layout1);
		bookList = new ArrayList<>();
		bookList.addAll(Cache.getNewOrTopBookListCache(3));
		topadapter = new HomePageListViewAdapter(this, bookList);
		lv_top.setAdapter(topadapter);

		tv_search.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				/*
				 * String key = et_key.getText().toString()+""; if
				 * (!TextUtils.isEmpty(key)) { search(key); }
				 */
				finish();
				overridePendingTransition(android.R.anim.fade_in,
						android.R.anim.fade_out);
			}
		});
		image_close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				et_key.setText("");
				setKey("");
				image_close.setVisibility(View.GONE);
				comprehensiveFragment.setSearchBean(new SearchBean());
				mrtFragment.setList(null);
				bookFragment.setList(null);
				anchorFragment.setList(null);
				et_key.requestFocus();
				InputMethodManager imm = (InputMethodManager) et_key
						.getContext().getSystemService(
								Context.INPUT_METHOD_SERVICE);
				imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
			}
		});
		et_key.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (!TextUtils.isEmpty(s)) {
					image_close.setVisibility(View.VISIBLE);
				} else {
					image_close.setVisibility(View.GONE);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
		et_key.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					String key = et_key.getText().toString() + "";
					if (!TextUtils.isEmpty(key)) {
						search(key);
					} else {
						CommonMethod.makeNotice(
								SearchActivity.this,
								getResources().getString(
										R.string.text_search_key_no_empty));
						return false;
					}
					return true;
				}
				return false;
			}
		});
	}

	private void initFragment() {
		comprehensiveFragment = new SearchComprehensiveFragment();
		mrtFragment = new SearchMrtFragment();
		bookFragment = new SearchBookFragment();
		anchorFragment = new SearchAnchorFragment();
		fragmentArrayList.add(comprehensiveFragment);
		fragmentArrayList.add(bookFragment);
		fragmentArrayList.add(anchorFragment);
		fragmentArrayList.add(mrtFragment);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(android.R.anim.fade_in,
				android.R.anim.fade_out);
	}

	/**
	 * 设置当前的滑动的位置
	 * 
	 * @param type
	 */
	public void setCurrentPage(String type) {
		switch (type) {
		case "m":
			viewPager.setCurrentItem(3);
			break;
		case "s":
			viewPager.setCurrentItem(1);
			break;
		case "z":
			viewPager.setCurrentItem(2);
			break;
		default:
			viewPager.setCurrentItem(0);
			break;
		}
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	private void search(String key) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String
				.valueOf(SharedPreferencesUtils.getParam(this,
						HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair("key", key + ""));
		HttpRequestHelper.executeHttpData(this, HttpRequestHelper.SEARCH_ALL,
				params, handle, HttpRequestHelper.GETDATA_SUCCESS,
				HttpRequestHelper.GETDATA_FAIL);
	}

	@Override
	protected void onDestroy() {
		TemporaryVariable.activities.removeElement(this);
		unRegisterEvent();
		super.onDestroy();
	}

	@Subscribe
	public void onEventPlayStute(Boolean isPlaying) {
		MusicPlayManager.getInstance(this).setPlaying(isPlaying);
		comprehensiveFragment.changePlayStute(isPlaying);
		bookFragment.changePlayStute(isPlaying);
	}

	public void registerEvent() {
		EventBus.getEventBus("m_play_stute", ThreadEnforcer.MAIN)
				.register(this);
	}

	public void unRegisterEvent() {
		EventBus.getEventBus("m_play_stute", ThreadEnforcer.MAIN).unregister(
				this);
	}
}
